from flask import render_template,redirect,url_for,session, flash
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef

from controller import app
from lib.form import Form
from dao.category import CategoryDao
from model.category import Category

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())

class CategoriesForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)

class CategoryForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)
        if self.is_submitted():
            # If get fail, return None
            self.action = self.request.values.get('action')
            
            if self.action == 'edit':
                self.id = self.request.values.get('id')
            else:
                self.id = None
                
            self.name = self.request.values.get('name')
            self.description = self.request.values.get('description')
            self.parent = self.request.values.get('parent')

@app.route('/manage_categories')
@app.route('/manage_categories', methods=['GET','POST'])
@login_required
def manage_categories():
    form = CategoryForm()
    category_dao = CategoryDao()
    
    if form.is_submitted():
        if form.action == 'edit':
            category = category_dao.update_category(form.id, form.name, form.description)
        else:
            _dict = {'name':form.name,'description':form.description}
            parent = category_dao.find_one({'name':form.parent})
            if parent is not None:
                _dict['parent'] = DBRef('addresses', parent._id)
            else:
                _dict['parent'] = None
            category_dao.save(_dict)
            
            #flash("Image saved.")
            #return redirect(url_for('pictures'))
            return redirect(url_for('display_categories'))
    return redirect(url_for('display_categories'))

@app.route('/display_categories')
@login_required
def display_categories():
    #return render_template("add_category-v1.html", categorys=None)
    
    category_dao = CategoryDao()
    _categories = category_dao.all()
    if len(_categories) == 0:
        return render_template("manage_categories.html", _categories=None)
    else:
        cats = []
        for _category in _categories:
            if _category.parent is not None:
                parent = category_dao.find_one({'_id':_category.parent.id})
                cats.append({"name":_category.name, "description":_category.description, "parent":parent.name})
            else:
                cats.append({"name":_category.name, "description":_category.description, "parent":"None"})
        
        return render_template("manage_categories.html", categories=cats)
    
@app.route("/delete_categories", methods=["GET", "POST"])
@login_required
def delete_categories():
    category_dao = CategoryDao()
    
    form = CategoriesForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        category = category_dao.filter_first(id=int(_id))
        category_dao.remove_from_db(category)
        
    return render_template("manage_categories.html", categories=category_dao.all())            
